//
//  CoreDataStack.m
//  CoreData
//
//  Created by ZRAR on 16/1/15.
//  Copyright © 2016年 ZRAR. All rights reserved.
//

#import "CoreDataStack.h"
#import "Person.h"


@interface CoreDataStack ()<NSFetchedResultsControllerDelegate>

@property (readwrite, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readwrite, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readwrite, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;

@end


@implementation CoreDataStack

+ (instancetype)defaultStack{
    
    static CoreDataStack *stack;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken,^{
        
        stack = [[self alloc] init];
    });
    
    return stack;
}

+ (instancetype)inMemoryStack{
    static CoreDataStack *stack;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken,^{
        stack = [[self alloc] init];
        //持久化存储协调者 ，包含数据存储的名字和位置，
        NSPersistentStoreCoordinator *persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[stack managedObjectModel]];
        NSError *error;
        if ([persistentStoreCoordinator addPersistentStoreWithType:NSInMemoryStoreType configuration:nil URL:nil options:nil error:&error]) {
            
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        }
        stack.persistentStoreCoordinator = persistentStoreCoordinator;
    });
    return stack;
}

- (void)saveContext{
    
    NSError *error = nil;

    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        
        if ([managedObjectContext hasChanges]&&![managedObjectContext save:&error]) {
            
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
        
    }
    
}

//管理对象的上下文，类似于应用程序和数据存储间的一块缓冲区，你可以增删改查管理对象
- (NSManagedObjectContext *)managedObjectContext{
    if (_managedObjectContext != nil) {
        
        return _managedObjectContext;
    }
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        
        _managedObjectContext = [[NSManagedObjectContext alloc] init];
        [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return _managedObjectContext;
}

//初始化必须依赖.momd文件路径，而.momd文件由.xcdatamodeld文件编译而来
- (NSManagedObjectModel *)managedObjectModel{
    
    if (_managedObjectModel != nil) {
        
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Person" withExtension:@"momd"];
    self.managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    
    return self.managedObjectModel;
}

//初始化必须依赖NSManagedObjectModel，之后要指定持久化存储的数据类型，默认的是NSSQLiteStoreType，即SQLite数据库；并指定存储路径为Documents目录下，以及数据库名称
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator{
    
    if (_persistentStoreCoordinator != nil) {
        
        return _persistentStoreCoordinator;
    }
    NSURL *storeUrl = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreData.sqlite"];
    NSError *error = nil;
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc]initWithManagedObjectModel:[self managedObjectModel]];
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error]) {
        
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);

    }
    return _persistentStoreCoordinator;
}

// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory {
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}




- (void)ensureInitialLoad{
    
    NSString *initialLoadKey = @"Initial Load";
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    BOOL hasInitiaLoad = [userDefaults boolForKey:initialLoadKey];
    if (hasInitiaLoad == NO) {
        
        [userDefaults setBool:YES forKey:initialLoadKey];
        {
            Person *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:[CoreDataStack defaultStack].managedObjectContext];
            person.name = @"zxh";
            person.phone = @"123456";
            person.email = @"email";
            person.adress = @"adress";
            person.header = @"Z";
        }
        
        [[CoreDataStack defaultStack] saveContext];
        
    }
    
    
    
}


@end
